rm(list=ls())

library(dplyr)
library(ggplot2)
library(magrittr)
library(rvest)
library(tidyverse)
library(leaflet)
library(RColorBrewer)
library(plotly)
library(readr)
library(tidyquant)
library(urbnmapr)
library(tmap)
library(sf)
library(stringr)
library(tigris)
library(rgdal)
library(WDI)
library(highcharter)
library(rworldmap)
library(tidyr)
library(igraph)
library(networkD3)

Covid Debt Surge

data <- read.csv("covid.csv")
data <- data %>%
  rename(Country = "X")


p <- ggplot(data = data, aes( x = Country, y = Debt_Increase)) +
  geom_bar(stat = "identity", fill = "dodgerblue1") +
  geom_text(aes(label=Debt_Increase), vjust = .5, hjust = 2, color="black", size=5) +
  scale_x_discrete(limits=c("China","France", "Spain", "United Kingdom", "Japan", "United States", "Canada")) +
  ggtitle("Debt to GDP Change in 2020") +
  xlab("Country") +
  labs(caption = "Bloomberg, IFF") +
  ylab("Percent Increase") +
  coord_flip() +
  theme_classic()

p +  theme(axis.text.x = element_text(face = "bold", colour = "black")) +
  theme(axis.text.y = element_text(face = "bold", colour = "black")) 

#US National Debt

d = read.csv("debt.csv")
us_debt = read.csv("federal_debt_trends.csv") 

usa = us_debt
usa = select(us_debt, year, federal_debt, gdp,debt_gdp)

# dot-and-line chart


usa_chart <- ggplot(usa, aes(x = year, y = debt_gdp,
                                             text = paste0("<b>Year: </b>", year,"<br>",
                                                           "<b>Debt: </b>", federal_debt," dollars<br>",
                                                           "<b>GDP: </b> $", gdp, " dollars<br>",
                                                          "<b>Debt GDP ratio: </b> ", debt_gdp, "(ratio)"),
                                             group = 1)) +
  xlab("Year") +
  ylab("Dollars ($)") +
  theme_minimal(base_size = 14, base_family = "Georgia") +
  geom_point() +
  geom_line()

usa_chart_interactive <- ggplotly(usa_chart, tooltip = "text") %>% 
  config(displayModeBar = FALSE) %>%
  layout(hoverlabel = list(bgcolor = "white",
                           font = list(family = "Georgia")))

usa_chart_interactive <- usa_chart_interactive %>% layout(title = 'US Debt to GDP Ratio')

print(usa_chart_interactive)

US State Debt

data <- read.csv("state_2020.csv") 
data_1 <- data %>%
  select(State, Debt.Ratio..Total.Debts.Total.Assets) %>%
  rename("Debt_Level" = "Debt.Ratio..Total.Debts.Total.Assets")

#Debt was recorded as a character, converted to numeric
data_1$Debt_Level <- str_remove_all(string = data_1$Debt_Level, pattern = "%")
data_1$Debt_Level <- as.numeric(data_1$Debt_Level)



# removing DC as it is a district
states_sf <- get_urbn_map("states", sf = TRUE)
states_sf <- states_sf %>%
  filter(state_abbv != "DC")

states_sf <- states_sf %>%
  rename(State = "state_name")

state_debt <- left_join(data_1, states_sf, by = "State")
#head(state_debt)

state_debt <- st_as_sf(state_debt)


position <- c("center", "top")
tm_shape(state_debt) + 
  tm_polygons(col = "Debt_Level", title = "Debt Level", palette = "Purples", breaks = c(0,25,50,75, 100, 150,200,300,400, 500)) +
  tm_text(text = "state_abbv", size = .75, remove.overlap = TRUE) +
  tm_legend(scale = .80) + 
  tm_layout(title = "State Debt Levels 2020 (%)", title.position = position) 

hdi = read.csv("human-development-index-escosura.csv")
hdiworld = hdi
#hdi

hdiworld <- hdiworld %>%
  filter(Year == 2015) %>%
  select(Entity, Historical.Index.of.Human.Development..Prados.de.la.Escosura.)  
#hdiworld
colnames(hdiworld)[colnames(hdiworld) == "Historical.Index.of.Human.Development..Prados.de.la.Escosura."] <- "HDI"
# Load required R packages


# Set highcharter options
options(highcharter.theme = hc_theme_smpl(tooltip = list(valueDecimals = 2)))

# Load the world Map data
data(worldgeojson, package = "highcharter")

#worldgeojson
hdiworld2 <-hdi
hdiworld2 <- hdiworld2 %>%
  filter(Year == 2015) %>%
  select(Code, Historical.Index.of.Human.Development..Prados.de.la.Escosura.)  

#hdiworld2
colnames(hdiworld2)[colnames(hdiworld2) == "Historical.Index.of.Human.Development..Prados.de.la.Escosura."] <- "HDI"

hc2 <- highchart() %>%
  hc_add_series_map(
    worldgeojson, hdiworld2, value = "HDI", joinBy = c('iso3','Code'),
    name = "HumanDevelopmentIndex"
    )  %>% 
  hc_colorAxis(stops = color_stops()) %>% 
  hc_title(text = "World Map") %>% 
  hc_subtitle(text = "HDI in 2015")

hc2
# create interactive line chart
graph3 = hdi

graph3 <- graph3 %>%
  select(Year, Entity, Historical.Index.of.Human.Development..Prados.de.la.Escosura.)  

colnames(graph3)[colnames(graph3) == "Historical.Index.of.Human.Development..Prados.de.la.Escosura."] <- "HDI"
#graph3

plotdata <- spread(graph3, Entity, HDI)

h <- highchart() %>% 
  hc_xAxis(categories = plotdata$Year) %>% 
  hc_add_series(name = "Argentina", 
                data = plotdata$Argentina) %>% 
  hc_add_series(name = "China", 
                data = plotdata$China) %>%
  hc_add_series(name = "India", 
                data = plotdata$India) %>%
  hc_add_series(name = "Peru", 
                data = plotdata$Peru) %>%
  hc_add_series(name = "United States of America", 
                data = plotdata$"United States") 

h <- h %>%
  hc_title(text = "HDI by Country",
           margin = 20, 
           align = "left",
           style = list(color = "steelblue")) %>% 
  hc_subtitle(text = "1870 to 2015",
              align = "left",
              style = list(color = "#2b908f", 
                           fontWeight = "bold")) %>% 
  hc_credits(enabled = TRUE, # add credits
             text = "United Nations HDI") %>% 
  hc_legend(align = "left", 
            verticalAlign = "top",
            layout = "vertical", 
            x = 0, 
            y = 100) %>%
  hc_tooltip(crosshairs = TRUE, 
             backgroundColor = "#FCFFC5",
             shared = TRUE, 
             borderWidth = 4) %>% 
  hc_exporting(enabled = TRUE)

h
world_debt = read_csv("world_debt - Sheet1.csv")
world_debt[world_debt == "no data"] <- NA
df_transpose = as.data.frame(t(world_debt))
names(df_transpose) <- lapply(df_transpose[1, ], as.character)
df_transpose <- df_transpose[-1,] 
world_debt_gdp_ratio = df_transpose
# generate graph
#Finding debt over time for:
#Argentina
#China
#India
#Peru
#US
world_debt_gdp_ratio = world_debt_gdp_ratio[2:48,] %>% mutate_if(is.character,as.double)

world_debt_gdp_ratio$Year = row.names(world_debt_gdp_ratio)

w <- highchart() %>% 
  hc_xAxis(categories = world_debt_gdp_ratio$Year) %>% 
  hc_add_series(name = "Argentina", 
                data = world_debt_gdp_ratio$Argentina,
                color = "#D55400") %>% 
  hc_add_series(name = "China", 
                data = world_debt_gdp_ratio$"China, People's Republic of",
                color = "#227FBB") %>% 
  hc_add_series(name = "India", 
                data = world_debt_gdp_ratio$India,
                color = "#1ECE6D") %>% 
  hc_add_series(name = "Peru", 
                data = world_debt_gdp_ratio$Peru,
                color = "#F2C500") %>% 
  hc_add_series(name = "United States of America", 
                data = world_debt_gdp_ratio$"United States",
                color= '#2B3E51') 


w
# customize interactive line chart
w <- w %>%
  hc_title(text = "Debt:GDP Ratio by Country",
           margin = 20, 
           align = "left",
           style = list(color = "steelblue")) %>% 
  hc_subtitle(text = "1980 to 2025",
              align = "left",
              style = list(color = "#2b908f", 
                           fontWeight = "bold")) %>% 
  hc_credits(enabled = TRUE, # add credits
             text = "IMF") %>% 
  hc_legend(align = "left", 
            verticalAlign = "top",
            layout = "vertical", 
            x = 0, 
            y = 100) %>%
  hc_tooltip(crosshairs = TRUE, 
             backgroundColor = "#FCFFC5",
             shared = TRUE, 
             borderWidth = 4) %>% 
  hc_exporting(enabled = TRUE)

w
w2 <- highchart() %>% 
  hc_xAxis(categories = world_debt_gdp_ratio$Year) %>% 
  hc_add_series(name = "Advanced Economies", 
                data = world_debt_gdp_ratio$`Advanced economies`) %>%
  hc_add_series(name = "Developing Countries", 
                data = world_debt_gdp_ratio$`Emerging market and developing economies`) 


w2
# customize interactive line chart
w2 <- w2 %>%
  hc_title(text = "Debt:GDP Ratio by Type",
           margin = 20, 
           align = "left",
           style = list(color = "steelblue")) %>% 
  hc_subtitle(text = "1930 to 2026",
              align = "left",
              style = list(color = "#2b908f", 
                           fontWeight = "bold")) %>% 
  hc_credits(enabled = TRUE, # add credits
             text = "world_debt_gdp_ratio") %>% 
  hc_legend(align = "left", 
            verticalAlign = "top",
            layout = "vertical", 
            x = 0, 
            y = 100) %>%
  hc_tooltip(crosshairs = TRUE, 
             backgroundColor = "#FCFFC5",
             shared = TRUE, 
             borderWidth = 4) %>% 
  hc_exporting(enabled = TRUE)

w2

dssi <- read_csv("dssi_2020.csv")

dssi <- dssi %>% select(-`Series Code`) %>% gather("Year", "Value", 6:9)

dssi <- dssi %>% anti_join(dssi[c(29785, 29786, 29787, 29788, 29789, 59574, 59575, 59576, 59577, 59578, 89363, 89364, 89365, 89366, 89367, 119152, 119153, 119154, 119155, 119156),])

dssi <- dssi %>% spread(`Series Name`, `Value`)

colnames(dssi) <- c("Debtor", "Debtor_Code", "Creditor", "Creditor_Code", "Year", "Debt_Forgiveness", "Debt_Stocks")

dssi$Debt_Forgiveness <- as.numeric(dssi$Debt_Forgiveness)
dssi$Debt_Stocks <- as.numeric(dssi$Debt_Stocks)
dssi$Year <- as.factor(dssi$Year)

dssi[is.na(dssi)] <- 0

dssi$Debtor <- stringr::str_trim(dssi$Debtor, side = "both")
dssi$Creditor <- stringr::str_trim(dssi$Creditor, side = "both")

dssi <- dssi %>% mutate(Debtor_Region = case_when(
  Debtor %in% c("Angola", "Benin", "Burkina Faso", "Burundi", "Cabo Verde", "Cameroon", "Central African Republic", "Chad", "Comoros", "Congo, Dem. Rep.", "Congo, Rep.", "Cote d'Ivoire", "Djibouti", "Ethiopia", "Gambia, The", "Ghana", "Guinea", "Guinea-Bissau", "Kenya", "Lesotho", "Liberia", "Madagascar", "Malawi", "Mali", "Mauritania", "Mozambique", "Niger", "Nigeria", "Rwanda", "Sao Tome and Principe", "Senegal", "Sierra Leone", "Somalia", "Tanzania", "Togo", "Uganda", "Zambia") ~ "Africa",
  Debtor %in% c("Bangladesh", "Bhutan", "Cambodia", "Kyrgyz Republic", "Lao PDR", "Maldives", "Mongolia", "Myanmar", "Nepal", "Pakistan", "Tajikistan", "Timor-Leste", "Uzbekistan") ~ "Asia",
  Debtor %in% c("Afghanistan", "Yemen, Rep.") ~ "Middle East",
  Debtor %in% c("Guyana", "Haiti", "Honduras", "Nicaragua") ~ "South & Central America",
  Debtor %in% c("Dominica", "Grenada", "St. Lucia", "St. Vincent and the Grenadines") ~ "The Caribbeans",
  Debtor %in% c("Fiji", "Papua New Guinea", "Samoa", "Solomon Islands", "Tonga", "Vanuatu") ~ "Pacific Islands",
  Debtor %in% c("Kosovo", "Moldova") ~ "Europe"
))
debt_series <- read_csv("debt_series.csv")

debt_series <- debt_series[1:68, c(1, 7:26)]
colnames(debt_series) <- c("Debtor", 2000:2019)
debt_series <- debt_series %>% gather(key = "Year", value = "Debt_Stocks", 2:21)

debt_series$Debt_Stocks <- as.numeric(debt_series$Debt_Stocks)
debt_series$Year <- as.numeric(debt_series$Year)

debt_series[which(is.na(debt_series$Debt_Stocks)), "Debt_Stocks"] <- 0

debt_series <- debt_series %>% mutate(Debtor_Region = case_when(
  Debtor %in% c("Angola", "Benin", "Burkina Faso", "Burundi", "Cabo Verde", "Cameroon", "Central African Republic", "Chad", "Comoros", "Congo, Dem. Rep.", "Congo, Rep.", "Cote d'Ivoire", "Djibouti", "Ethiopia", "Gambia, The", "Ghana", "Guinea", "Guinea-Bissau", "Kenya", "Lesotho", "Liberia", "Madagascar", "Malawi", "Mali", "Mauritania", "Mozambique", "Niger", "Nigeria", "Rwanda", "Sao Tome and Principe", "Senegal", "Sierra Leone", "Somalia", "Tanzania", "Togo", "Uganda", "Zambia") ~ "Africa",
  Debtor %in% c("Bangladesh", "Bhutan", "Cambodia", "Kyrgyz Republic", "Lao PDR", "Maldives", "Mongolia", "Myanmar", "Nepal", "Pakistan", "Tajikistan", "Timor-Leste", "Uzbekistan") ~ "Asia",
  Debtor %in% c("Afghanistan", "Yemen, Rep.") ~ "Middle East",
  Debtor %in% c("Guyana", "Haiti", "Honduras", "Nicaragua") ~ "South & Central America",
  Debtor %in% c("Dominica", "Grenada", "St. Lucia", "St. Vincent and the Grenadines") ~ "The Caribbeans",
  Debtor %in% c("Fiji", "Papua New Guinea", "Samoa", "Solomon Islands", "Tonga", "Vanuatu") ~ "Pacific Islands",
  Debtor %in% c("Kosovo", "Moldova") ~ "Europe"
))
selected_creditors <- read_csv("selected_creditors.csv")

selected_creditors <- selected_creditors %>% select(-`Series Code`)
colnames(selected_creditors) <- c("Debtor", "Debtor_Code", "Creditor", "Creditor_Code", "Series", 2000:2019)

selected_creditors <- selected_creditors %>% gather("year", "value", 6:25)

selected_creditors[which(selected_creditors$Series == "External debt stocks, total (DOD, current US$)"), "Series"] <- "Debt_Stocks"
selected_creditors[which(selected_creditors$Series == "Debt forgiveness or reduction (current US$)"), "Series"] <- "Debt_Forgiveness"

selected_creditors <- selected_creditors %>% filter(!is.na(Series))

selected_creditors <- spread(selected_creditors, Series, value)


selected_creditors$Debt_Forgiveness <- as.numeric(selected_creditors$Debt_Forgiveness)
selected_creditors$Debt_Stocks <- as.numeric(selected_creditors$Debt_Stocks)
selected_creditors$year <- as.numeric(selected_creditors$year)

selected_creditors[is.na(selected_creditors)] <- 0

selected_creditors$Debtor <- stringr::str_trim(selected_creditors$Debtor, side = "both")
selected_creditors$Creditor <- stringr::str_trim(selected_creditors$Creditor, side = "both")

selected_creditors <- selected_creditors %>% mutate(Debtor_Region = case_when(
  Debtor %in% c("Angola", "Benin", "Burkina Faso", "Burundi", "Cabo Verde", "Cameroon", "Central African Republic", "Chad", "Comoros", "Congo, Dem. Rep.", "Congo, Rep.", "Cote d'Ivoire", "Djibouti", "Ethiopia", "Gambia, The", "Ghana", "Guinea", "Guinea-Bissau", "Kenya", "Lesotho", "Liberia", "Madagascar", "Malawi", "Mali", "Mauritania", "Mozambique", "Niger", "Nigeria", "Rwanda", "Sao Tome and Principe", "Senegal", "Sierra Leone", "Somalia", "Tanzania", "Togo", "Uganda", "Zambia") ~ "Africa",
  Debtor %in% c("Bangladesh", "Bhutan", "Cambodia", "Kyrgyz Republic", "Lao PDR", "Maldives", "Mongolia", "Myanmar", "Nepal", "Pakistan", "Tajikistan", "Timor-Leste", "Uzbekistan") ~ "Asia",
  Debtor %in% c("Afghanistan", "Yemen, Rep.") ~ "Middle East",
  Debtor %in% c("Guyana", "Haiti", "Honduras", "Nicaragua") ~ "South & Central America",
  Debtor %in% c("Dominica", "Grenada", "St. Lucia", "St. Vincent and the Grenadines") ~ "The Caribbeans",
  Debtor %in% c("Fiji", "Papua New Guinea", "Samoa", "Solomon Islands", "Tonga", "Vanuatu") ~ "Pacific Islands",
  Debtor %in% c("Kosovo", "Moldova") ~ "Europe"
))
ggplotly(debt_series %>% group_by(Debtor_Region, Year) %>% summarize(total_debt_bil = sum(Debt_Stocks)/10^9 %>% round(digits = 2), mean_debt_bil = mean(Debt_Stocks)/10^9 %>% round(digits = 2)) %>% ggplot() + geom_line(aes(x = Year, y = total_debt_bil, color = Debtor_Region)) + labs(y = "Total debt (billions of US$)", title = "Total debt per region over time") + theme_minimal())
ggplotly(debt_series %>% group_by(Debtor_Region, Year) %>% summarize(total_debt_bil = sum(Debt_Stocks)/10^9 %>% round(digits = 2), mean_debt_bil = mean(Debt_Stocks)/10^9 %>% round(digits = 2)) %>% ggplot() + geom_line(aes(x = Year, y = mean_debt_bil, color = Debtor_Region)) + labs(y = "Mean debt (billions of US$)", title = "Mean debt per region over time") + theme_minimal())
creditors_years <- selected_creditors %>% group_by(Creditor, year) %>% summarize(total_lending_bil = sum(Debt_Stocks)/10^9)


ggplotly(ggplot(creditors_years) + geom_line(aes(x = year, y = total_lending_bil, color = Creditor)) + labs(x = "Year", y = "Total lending (billions of US$)", title = "Total lending over time (selected creditors)") + theme_minimal()) 
ggplotly(ggplot(creditors_years %>% filter(Creditor %in% c("China", "Japan", "United States", "United Kingdom", "France", "Saudi Arabia", "India"))) + geom_line(aes(x = year, y = total_lending_bil, color = Creditor)) + labs(x = "Year", y = "Total lending (billions of US$)", title = "Total lending over time (selected creditors)") + theme_minimal())
debt_2000 <- dssi %>% filter(Year == 2000)
debt_2019 <- dssi %>% filter(Year == 2019)
debt_2000 %>% group_by(Creditor) %>% summarize(total_lending_bil = sum(Debt_Stocks)/10^9) %>% arrange(desc(total_lending_bil))
## # A tibble: 219 x 2
##    Creditor                    total_lending_bil
##    <chr>                                   <dbl>
##  1 World                                   262. 
##  2 World Bank-IDA                           49.0
##  3 Multiple Lenders                         26.8
##  4 Other Multiple Lenders                   21.7
##  5 Japan                                    20.5
##  6 Asian Dev. Bank                          14.0
##  7 France                                   13.9
##  8 International Monetary Fund              12.6
##  9 Russian Federation                       11.4
## 10 African Dev. Bank                        10.9
## # … with 209 more rows
debt_2019 %>% group_by(Creditor) %>% summarize(total_lending_bil = sum(Debt_Stocks)/10^9) %>% arrange(desc(total_lending_bil))
## # A tibble: 219 x 2
##    Creditor                    total_lending_bil
##    <chr>                                   <dbl>
##  1 World                                   744. 
##  2 Other Multiple Lenders                  203. 
##  3 World Bank-IDA                          111. 
##  4 China                                   109. 
##  5 Bondholders                              76.3
##  6 Asian Dev. Bank                          36.2
##  7 International Monetary Fund              32.4
##  8 Other Multilaterals                      31.2
##  9 Japan                                    24.1
## 10 African Dev. Bank                        23.1
## # … with 209 more rows
cols <- RColorBrewer::brewer.pal(8, "Dark2")

top_creditors_2000 <- debt_2000 %>% filter(!Creditor %in% c("World", "Multiple Lenders", "Other Multiple Lenders", "Other Multilaterals", "Bondholders", "Other Bilateral")) %>% group_by(Creditor) %>% summarize(total_debt_bil = sum(Debt_Stocks)/10^9 %>% round(digits = 3)) %>% arrange(desc(total_debt_bil)) %>% head(n = 20)

top_creditors_2019 <- debt_2019 %>% filter(!Creditor %in% c("World", "Multiple Lenders", "Other Multiple Lenders", "Other Multilaterals", "Bondholders", "Other Bilateral")) %>% group_by(Creditor) %>% summarize(total_debt_bil = sum(Debt_Stocks)/10^9 %>% round(digits = 3)) %>% arrange(desc(total_debt_bil)) %>% head(n = 20) 

top_creditors_2000 %>% hchart("pie", hcaes(x = Creditor, y = round(total_debt_bil, digits = 1)), name = "Total Lending (billions of US$)") %>% hc_title(text = "Top creditors in 2000")  %>% hc_caption(text = "Data: The World Bank (2021)") %>% hc_colors(cols)
top_creditors_2019 %>% hchart("pie", hcaes(x = Creditor, y = round(total_debt_bil, digits = 1)), name = "Total Lending (billions of US$)") %>% hc_title(text = "Top creditors in 2019")  %>% hc_caption(text = "Data: The World Bank (2021)") %>% hc_colors(cols)
links_2019 <- debt_2019 %>% select(Debtor, Creditor, Debt_Stocks) %>% filter(Debt_Stocks != 0) %>% filter(!Creditor %in% c("Other Bilateral", "Other Multiple Lenders", "Other Multilaterals", "World", "Multiple Lenders", "Bondholders"))

links_2019 <- links_2019[, c(2, 1, 3)]

links_2019$Debt_Stocks <- links_2019$Debt_Stocks/10^9 

debtors_2019 <- links_2019 %>% group_by(Debtor) %>% summarize(size = sum(Debt_Stocks))
debtors_2019$group <- "Debtor"
debtors_2019 <- debtors_2019 %>% rename(name = Debtor)

creditors_2019 <- links_2019 %>% group_by(Creditor) %>% summarize(size = sum(Debt_Stocks))
creditors_2019$group <- "Creditor"
creditors_2019 <- creditors_2019 %>% rename(name = Creditor)

nodes_2019 <- rbind(debtors_2019, creditors_2019)

nodes_2019 <- as.data.frame(nodes_2019)
links_2019 <- as.data.frame(links_2019)

nodes_2019$id <- 1:nrow(nodes_2019)

nodes_2019 <- nodes_2019 %>% mutate(region = case_when(
  name %in% c("Angola", "Benin", "Burkina Faso", "Burundi", "Cabo Verde", "Cameroon", "Central African Republic", "Chad", "Comoros", "Congo, Dem. Rep.", "Congo, Rep.", "Cote d'Ivoire", "Djibouti", "Ethiopia", "Gambia, The", "Ghana", "Guinea", "Guinea-Bissau", "Kenya", "Lesotho", "Liberia", "Madagascar", "Malawi", "Mali", "Mauritania", "Mozambique", "Niger", "Nigeria", "Rwanda", "Sao Tome and Principe", "Senegal", "Sierra Leone", "Somalia", "Tanzania", "Togo", "Uganda", "Zambia", "Cote D`Ivoire, Republic Of", "Libya", "Mauritius", "South Africa") ~ "Africa",
  name %in% c("Bangladesh", "Bhutan", "Cambodia", "Kyrgyz Republic", "Lao PDR", "Maldives", "Mongolia", "Myanmar", "Nepal", "Pakistan", "Tajikistan", "Timor-Leste", "Uzbekistan", "China", "Hong Kong", "India", "Japan", "Korea, Republic Of", "Kuwait", "Malaysia", "Singapore", "Sri Lanka", "Thailand") ~ "Asia",
  name %in% c("Afghanistan", "Yemen, Rep.", "Bahrain", "Egypt", "Iran, Islamic Republic Of", "Israel", "Saudi Arabia", "United Arab Emirates") ~ "Middle East",
  name %in% c("Guyana", "Haiti", "Honduras", "Nicaragua", "Brazil", "Venezuela, Republic Bolivarian") ~ "South & Central America",
  name %in% c("Dominica", "Grenada", "St. Lucia", "St. Vincent and the Grenadines", "Bahamas", "Barbados", "St. Kitts And Nevis", "Trinidad & Tobago", "St. Vincent & The Grenadines") ~ "The Caribbeans",
  name %in% c("Canada", "United States") ~ "North America", 
  name %in% c("Fiji", "Papua New Guinea", "Samoa", "Solomon Islands", "Tonga", "Vanuatu", "Australia") ~ "Oceania",
  name %in% c("Kosovo", "Moldova", "Argentina", "Austria", "Belarus", "Belgium", "Czech Republic", "Denmark", "Finland", "France", "Germany, Fed.Rep. Of", "Greece", "Hungary", "Ireland", "Italy", "Netherlands", "Norway", "Poland", "Portugal", "Russian Federation", "Serbia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "United Kingdom") ~ "Europe",
  name %in% c("African Dev. Bank", "Asian Dev. Bank", "Inter-American Dev. Bank", "International Monetary Fund", "World Bank-IBRD", "World Bank-IDA") ~ "Organizations"
))


links_2019 <- left_join(links_2019, nodes_2019 %>% select(name, id), by = c("Creditor" = "name"))
links_2019 <- left_join(links_2019, nodes_2019 %>% select(name, id), by = c("Debtor" = "name"))

links_2019 <- links_2019 %>% rename(source = id.x, target = id.y)

links_2019$source <- links_2019$source - 1
links_2019$target <- links_2019$target - 1
script <- 'alert("Name: " + d.name + "\\n" + "Status: " + d.status + "\\n" + "Region: " + d.group + "\\n" + "Total debt/lending (billions of US$): " + d.size);'

network_2019 <- forceNetwork(Links = links_2019, 
                   Nodes = nodes_2019, 
                   Source = "source",
                   Target = "target", 
                   Value = "Debt_Stocks", 
                   NodeID = "name",
                   Nodesize = "size",
                   Group = "region", 
             fontSize = 20,
             linkDistance = 80,
                   opacity = 0.9, zoom = TRUE, legend = TRUE, arrows = TRUE, height = 500, width = 1000, bounded = TRUE, clickAction = script)



network_2019$x$nodes$status <- nodes_2019$group
network_2019$x$nodes$size <- nodes_2019$size %>% round(digits = 3)


## Click on the node to see info popup
network_2019

Apendix

#line chart
usa_chart <- ggplot(usa, aes(x = year, y = debt_gdp)) +
  xlab("Year") +
  ylab("Debt-GDP") +
  theme_minimal(base_size = 14, base_family = "Georgia")+
  geom_point() +
  geom_line()

plot(usa_chart)

usa_chart_interactive <- ggplotly(usa_chart)
print(usa_chart_interactive)


h